package cn.guetzjb.sys.service.impl;

import cn.guetzjb.sys.domain.RoleUsers;
import cn.guetzjb.sys.domain.SysRole;
import cn.guetzjb.sys.domain.SysUser;
import cn.guetzjb.sys.domain.SysUserRole;
import cn.guetzjb.sys.mapper.SysUserMapper;
import cn.guetzjb.sys.mapper.SysUserRoleMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.guetzjb.sys.service.SysRoleService;
import cn.guetzjb.sys.mapper.SysRoleMapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author admin
 * @description 针对表【sys_role(角色信息表)】的数据库操作Service实现
 * @createDate 2023-12-18 10:05:58
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
        implements SysRoleService {

    private final SysUserRoleMapper userRoleMapper;
    private final SysUserMapper userMapper;

    @Override
    public List<SysRole> getRoleToUsers() {
        MPJLambdaWrapper<SysRole> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(SysRole.class)
                .selectAll(SysUser.class)
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId)
                .selectCollection(SysUser.class, SysRole::getSysUserList);
        List<SysRole> list = baseMapper.selectJoinList(SysRole.class, wrapper);
        Set<Long> hasRoleUserKeys = userRoleMapper.selectList(Wrappers.emptyWrapper()).stream().map(SysUserRole::getUserId).collect(Collectors.toSet());
        List<SysUser> sysUsers = userMapper.selectList(Wrappers.<SysUser>lambdaQuery().notIn(SysUser::getUserId, hasRoleUserKeys));
        if (!sysUsers.isEmpty()) {
            SysRole sysRole = new SysRole();
            sysRole.setRoleId(-1L);
            sysRole.setRoleName("未分配");
            sysRole.setRoleKey("empty");
            sysRole.setSysUserList(sysUsers);
            list.add(sysRole);
        }
        return list;
    }
}




